<template>
  <span v-if="props.showText">{{ message }}</span>
  <el-checkbox-group
    v-else
    v-model="checkedValue"
    @change="handleChange"
  >
    <el-checkbox
      v-for="item in options" 
      :key="item.key"
      :value="item.key"
    >{{item.value}}</el-checkbox>
  </el-checkbox-group>
</template>

<script setup>
import { ref, watch } from 'vue';

const modelValue = defineModel();
const emit = defineEmits(['change']);
const props = defineProps({
  dictCode: String,
  options: [Array, String],
  showText: {
    type: Boolean,
    default: false
  }
});
const message = ref();
const options = ref([]);
const checkedValue = ref([]);

const handleChange = (event) => {
  if (checkedValue.value) {
    modelValue.value = checkedValue.value.join(',');
  }
  emit('change', event);
};

const init = (data) => {
  if (data) {
    if (Array.isArray(data)) {
      options.value = data;
    } else if (typeof data === 'string') {
      const optionList = [];
      data.split(',').forEach(item => {
        optionList.push({key: item, value: item});
      });
      options.value = optionList;
    }
  }
  calcValue();
};

const calcValue = () => {
  if (options.value == null || options.value.length <= 0) {
    message.value = '';
  } else {
    const names = [];
    checkedValue.value.forEach(id => {
      const find = options.value.find(item => item.key === id);
      if (find) {
        names.push(find.value);
      }
    });
    message.value = names.join(',');
  }
};

watch(() => modelValue.value, (data) => {
  if (data) {
    checkedValue.value = data.split(',');
    calcValue();
  } else {
    checkedValue.value = [];
    message.value = '';
  }
}, {immediate: true});

watch(() => props.options, (data) => {
  init(data);
}, {immediate: true});
</script>